package com.fw.controller;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fw.model.Role;
import com.fw.model.User;
import com.fw.service.RoleService;
import com.fw.service.UserService;
import com.fw.service.impl.RoleServiceImpl;
import com.fw.service.impl.UserServiceImpl;
import com.fw.util.MD5Utils;
import com.fw.util.SessionUser;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
public class UserController extends Controller {
	UserService userService = null;
	RoleService roleService = null;
	/**
	 * 登录
	 */
	@Clear
	public void login() {
		User user = getModel(User.class);
		userService = new UserServiceImpl();
		User u = userService.query_userByUNameAndUPwdService(user);
		if(u!=null){
			Integer rid = null;
			List<Role> roles = u.getRoles();
			if(roles.size()>0) rid = roles.get(0).getInt("r_id"); 
			setSessionAttr("sessionUser", new SessionUser(u.getInt("u_id"), u.getStr("u_name"),u.getStr("u_email"),rid));
			redirect("/common/index");
		}
		else{
			String message = "用户名或密码错误，请重新登录";
			setAttr("message", message);
			renderJsp("/WEB-INF/jsp/cue_message.jsp");
		}
			
	}
	public void toUserListView(){
		renderJsp("/WEB-INF/jsp/user_list.jsp");
	}
	public void query_allUserByPage() throws UnsupportedEncodingException{
		Gson gson = new GsonBuilder().registerTypeAdapter(User.class, new JsonSerializer<User>() {
			@Override
			public JsonElement serialize(User user, Type arg1,JsonSerializationContext arg2) {
				JsonObject o = new JsonObject();
				o.addProperty("u_id", user.getInt("u_id"));
				o.addProperty("u_email", user.getStr("u_email"));
				o.addProperty("u_name", user.getStr("u_name"));
				o.addProperty("u_status", user.getInt("u_status"));
				return o;
			}
		}).create();
		StringBuffer sql = new StringBuffer();
		HttpServletRequest request = getRequest();
		request.setCharacterEncoding("utf-8");
		HttpServletResponse response = getResponse();
		response.setContentType("text/html;charset = utf-8");
		//显示的起始索引
		int limitStart = Integer.parseInt(getPara("start").toString());
		//显示的行数
		int limitLength = Integer.parseInt(getPara("length").toString());
		String draw = "0";
		draw = getPara("draw");
		//排序字段
//			String dispOrderStr = getPara("mDataProp_"+getPara("iSortCol_0").toString()).toString();
		//升序还是降序 desc 和 asc
//			String sSortDir =  getPara("sSortDir_0").toString().trim();
//			if(dispOrderStr!=null && sSortDir!=null){
//				sql.append(" ORDER BY u."+dispOrderStr+" "+sSortDir);
//			}
		userService = new UserServiceImpl();
		int totalData = userService.query_totalUserService(sql.toString());
		List<User> list = userService.query_allUserByPageService(sql.toString(), limitStart, limitLength);
		Map<Object, Object> info = new HashMap<Object, Object>();
		info.put("data",gson.fromJson(gson.toJson(list),List.class));
		info.put("recordsTotal", totalData);
		info.put("recordsFiltered", totalData);
		info.put("draw", draw);
		renderJson(info);
	}
	public void delete_userById(){
		User user = getModel(User.class);
		userService = new UserServiceImpl();
		boolean flag = userService.delete_userByIdService(user);
		renderJson(flag);
	}
	public void toAddUserView(){
		renderJsp("/WEB-INF/jsp/add_user.jsp");
	}
	public void addUser(){
		User user = getModel(User.class);
		userService = new UserServiceImpl();
		String pwd = user.getStr("u_pwd");
		user.put("u_pwd",MD5Utils.getInstance().getStringHash(pwd));
		boolean flag = userService.add_userService(user);
		String message = null;
		if(flag){
			message = "添加成功";
			setAttr("message", message);
		}
		else{
			message = "添加失败";
			setAttr("message", message);
		} 
		renderJsp("/WEB-INF/jsp/cue_message.jsp");
	}
	public void updateUser(){
		User user = getModel(User.class);
		userService = new UserServiceImpl();
		String pwd = user.getStr("u_pwd");
		user.put("u_pwd",MD5Utils.getInstance().getStringHash(pwd));
		String message = null;
		if(userService.update_userService(user)){
			message = "修改成功";
			setAttr("message", message);
		}
		else{
			message = "修改失败";
			setAttr("message", message);
		}
		renderJsp("/WEB-INF/jsp/cue_message.jsp");
	}
	public void toUpdateUserView(){
		User user = getModel(User.class);
		userService = new UserServiceImpl();
		User u = userService.query_userByIdService(user);
		setAttr("user", u);
		renderJsp("/WEB-INF/jsp/update_user.jsp");
	}
	public void toUserRoleView(){
		User user = getModel(User.class);
		roleService = new RoleServiceImpl();
		userService = new UserServiceImpl();
		setAttr("rs", roleService.query_allRoleService());
		Role r = userService.query_roleByUserService(user);
		setAttr("role", r);
		setAttr("u_id", user.getInt("u_id"));
		renderJsp("/WEB-INF/jsp/user_role.jsp");
	}
	public void updateUserRole(){
		Integer optionsRadios = getParaToInt("optionsRadios");
		User u = getModel(User.class);
		Role r = new Role().set("r_id",optionsRadios);
		userService = new UserServiceImpl();
		boolean flag = userService.update_roleByUserService(u,r);
		String message = null;
		if(flag){
			message = "分配成功";
			setAttr("message",message);
		}
		else {
			message = "分配失败";
			setAttr("message",message);
		}
		renderJsp("/WEB-INF/jsp/cue_message.jsp");
	}
	public void toUpdateUserPwdView(){
		User u = getModel(User.class);
		setAttr("user", u);
		renderJsp("/WEB-INF/jsp/update_user_pwd.jsp");
	}
	public void update_user_pwd(){
		User user = getModel(User.class);
		userService = new UserServiceImpl();
		boolean flag = userService.update_user_pwdService(user);
		String message = null;
		if(flag){
			message = "分配成功";
			setAttr("message",message);
		}
		else {
			message = "分配失败";
			setAttr("message",message);
		}
		renderJsp("/WEB-INF/jsp/cue_message.jsp");
	}
	
}
